package com.clouddot.baipai.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.clouddot.baipai.R;
import com.clouddot.baipai.component.DaggerIV_SMainActivityComponent;
import com.clouddot.baipai.contract.IH_SMainActivityContract;
import com.clouddot.baipai.http.entity.response.getBanPaiModelResponse;
import com.clouddot.baipai.http.entity.response.getClassInfoResponse;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.infrastructure.environment.environment;
import com.clouddot.baipai.module.H_SMainActivityModule;
import com.clouddot.baipai.ui.Dialog.A_KeyDailog;
import com.clouddot.baipai.ui.fragment.A_TableFrgment;
import com.clouddot.baipai.ui.fragment.V.V_AttendFrgment;
import com.clouddot.baipai.ui.fragment.V.V_ClassFrgment;
import com.clouddot.baipai.ui.fragment.V.V_HomeWorkFrgment;
import com.clouddot.baipai.ui.fragment.V.V_MainFrgment;
import com.clouddot.baipai.ui.fragment.V.V_NewsFrgment;
import com.clouddot.baipai.ui.fragment.V.V_PersonFrgment;
import com.clouddot.baipai.ui.fragment.V.V_SchoolFrgment;
import com.clouddot.baipai.util.EscapeUnescapeUtil;
import com.clouddot.baipai.util.SelectedBtnUtil;
import com.clouddot.baipai.util.ThreadPool.ThreadPoolFactory;
import com.clouddot.baipai.util.Toast.ToastUtil;
import com.clouddot.baipai.util.viewUtil.getTimeAndWeatherUtil;
import com.xiao.nicevideoplayer.NiceVideoPlayerManager;

import org.wxy.sdk.base.IBasePresenter;
import org.wxy.sdk.base.impl.BaseFragment;

import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import android_serialport_api.sample.SerialPortActivity;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wxy on 2018/05/27.
 *
 * @author wxy
 * @date on 2018/05/27 11:32
 * 竖屏 的主页面
 */

public class V_SMainActivity extends SerialPortActivity implements IH_SMainActivityContract.IView {

    public static final int MSG_ONE = 1;
    public static final int MSG_TWO = 2;
    public static final int MSG_THREE = 3;
    private boolean isActivity = false;

    private boolean isLockSet = false;
    private boolean isLock = true;
    private boolean isScanCard = false;
    /*** 判断当前刷卡机制是否在运行*/
    private LinearLayout[] linearLayouts = new LinearLayout[8];
    private BaseFragment[] fragments = new BaseFragment[8];
    private List<Map<String, String>> mapList;
    /**
     * 存放天气预报信息
     */

    private static int currentLoginTime = -1;
    public static int backTime = -1;
    private String cardCode = "";

    @Inject
    IH_SMainActivityContract.IPresenter mPresenter;
    @BindView(R.id.home1)
    LinearLayout home1;
    @BindView(R.id.home2)
    LinearLayout home2;
    @BindView(R.id.home3)
    LinearLayout home3;
    @BindView(R.id.home4)
    LinearLayout home4;
    @BindView(R.id.home5)
    LinearLayout home5;
    @BindView(R.id.home6)
    LinearLayout home6;
    @BindView(R.id.home7)
    LinearLayout home7;
    //    @BindView(R.id.home8)
//    LinearLayout home8;
    @BindView(R.id.home9)
    LinearLayout home9;
    @BindView(R.id.img1)
    ImageView img;

    @BindView(R.id.weatherIcon)
    ImageView weatherIcon;
    @BindView(R.id.tv_className)
    TextView tv_className;
    @BindView(R.id.tvloginTime)
    TextView tvloginTime;

    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.tv_data)
    TextView tv_data;
    @BindView(R.id.img_setting)
    ImageView img_setting;
    @BindView(R.id.img_loginTime)
    ImageView img_loginTime;

    @BindView(R.id.scrollView)
    HorizontalScrollView scrollView;

    @Override
    protected int getContentViewId() {
        return R.layout.v_activity_main;
    }

    @Override
    protected void initVariables() {
        environment.getInstance().activities.add(this);
        DaggerIV_SMainActivityComponent.builder().h_SMainActivityModule(new H_SMainActivityModule(this)).build().inject(this);
        if (Env.getAppContext().isInitial) {
            mPresenter.getClassInfo(Env.getAppContext().carddevid);
            mPresenter.getWeather("101270101");
        }
    }


    @Override
    protected void initViews() {
        linearLayouts[0] = home1;
        linearLayouts[1] = home2;
        linearLayouts[2] = home3;
        linearLayouts[3] = home4;
        linearLayouts[4] = home5;
        linearLayouts[5] = home6;
        linearLayouts[6] = home7;
//        linearLayouts[7] = home8;
        linearLayouts[7] = home9;
        fragments[0] = new V_MainFrgment();
        fragments[1] = new V_SchoolFrgment();
        fragments[2] = new V_ClassFrgment();
        fragments[3] = new V_NewsFrgment();
        fragments[4] = new A_TableFrgment();
        fragments[5] = new V_AttendFrgment();
        fragments[6] = new V_HomeWorkFrgment();
        fragments[7] = new V_PersonFrgment();
        SelectedBtnUtil.selectedforLinear(linearLayouts, linearLayouts[0]);

        ThreadPoolFactory.getThread().execute(getTimeBySecond);
        getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(UiVisibilityChangeListener);
    }

    @Override
    public void onBackPressed() {
        if (NiceVideoPlayerManager.instance().onBackPressd()) return;
        super.onBackPressed();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (Env.getAppContext().isInitial) {
            HideFragment(fragments[0]);
            mPresenter.getClassInfo(Env.getAppContext().carddevid);
            mPresenter.getWeather("101270101");
            currentLoginTime = 0;
        }
    }

    @Override
    protected void loadData() {
    }

    @Override
    public IBasePresenter getPresenter() {
        return mPresenter;
    }

    @OnClick({R.id.home1, R.id.home2, R.id.home3, R.id.home4, R.id.home5, R.id.home6, R.id.home7, R.id.home9, R.id.img_setting,R.id.main_bottom_left,R.id.main_bottom_right})
    public void onClick(View view) {
        if (Env.getAppContext().isInitial) {
            backTime = Env.getAppContext().backToMainTime * 60;
            switch (view.getId()) {
                case R.id.home1:
                    backTime = -1;
                    SelectedBtnUtil.selectedforLinear(linearLayouts, linearLayouts[0]);
                    replaceFragment(R.id.fragmentP, fragments[0]);
                    break;
                case R.id.home2:
                    SelectedBtnUtil.selectedforLinear(linearLayouts, linearLayouts[1]);
                    replaceFragment(R.id.fragmentP, fragments[1]);
                    break;
                case R.id.home3:
                    SelectedBtnUtil.selectedforLinear(linearLayouts, linearLayouts[2]);
                    scrollView.arrowScroll(view.FOCUS_LEFT);
                    replaceFragment(R.id.fragmentP, fragments[2]);
                    break;
                case R.id.home4:
                    SelectedBtnUtil.selectedforLinear(linearLayouts, linearLayouts[3]);
                    scrollView.arrowScroll(view.FOCUS_LEFT);
                    replaceFragment(R.id.fragmentP, fragments[3]);
                    break;
                case R.id.home5:
                    SelectedBtnUtil.selectedforLinear(linearLayouts, linearLayouts[4]);
                    scrollView.arrowScroll(view.FOCUS_RIGHT);
                    replaceFragment(R.id.fragmentP, fragments[4]);
                    break;
                case R.id.home6:
                    SelectedBtnUtil.selectedforLinear(linearLayouts, linearLayouts[5]);
                    scrollView.arrowScroll(view.FOCUS_RIGHT);
                    replaceFragment(R.id.fragmentP, fragments[5]);
                    break;
                case R.id.home7:
                    SelectedBtnUtil.selectedforLinear(linearLayouts, linearLayouts[6]);
                    replaceFragment(R.id.fragmentP, fragments[6]);
                    break;
//                case R.id.home8:
//                    SelectedBtnUtil.selectedforLinear(linearLayouts, linearLayouts[7]);
//                    replaceFragment(R.id.fragmentP, fragments[7]);
//                    break;
                case R.id.home9:
                    SelectedBtnUtil.selectedforLinear(linearLayouts, linearLayouts[7]);
                    replaceFragment(R.id.fragmentP, fragments[7]);

                    break;
                case R.id.img_setting:
                    //startActivityForResult(new Intent(V_SMainActivity.this, SettingActivity.class), COMETOSET);
                    A_KeyDailog dailog = new A_KeyDailog(V_SMainActivity.this);
                    dailog.showDialog();
                    break;

                case R.id.main_bottom_left:
                    scrollView.arrowScroll(view.FOCUS_LEFT);
                    break;

                case R.id.main_bottom_right:
                    scrollView.arrowScroll(view.FOCUS_RIGHT);
                    break;
            }
        } else {
            ToastUtil.showToast(this, "服务器IP空,请填写");
            startActivityForResult(new Intent(V_SMainActivity.this, SettingActivity.class), COMETOSET);
        }
    }

    /**
     * @param flag   不同的标识代表不同的请求返回的结果
     *               1.获取班级信息
     *               2.获取班级信息
     *               3.获取个人信息
     *               4.获取天气
     *               5.班牌模式
     * @param object
     */
    @Override
    public void success(int flag, Object object) {
        if (flag == 1) { //获取班级信息
            getClassInfoResponse response = (getClassInfoResponse) object;
            tv_className.setText(response.ClassName);
            addFragment(R.id.fragmentP, fragments[0]);
//            mPresenter.login("37547757833");
        } else if (flag == 2) { //登录成功
            mPresenter.getPerson();
        } else if (flag == 3) { //获取个人信息
            isScanCard = false;
            currentLoginTime = Env.getAppContext().LoginTime;
            tvloginTime.setVisibility(View.VISIBLE);
            img_loginTime.setVisibility(View.VISIBLE);
            home9.performClick();
        } else if (flag == 4) { //.获取天气
            mapList = (List<Map<String, String>>) object;
            if (mapList.size() > 1) {
                String weather = mapList.get(41).get("type");
                if (weather.contains("雨")) {
                    weatherIcon.setBackgroundResource(R.drawable.rain);
                } else if (weather.contains("云")) {
                    weatherIcon.setBackgroundResource(R.drawable.cloud);
                } else if (weather.contains("阴")) {
                    weatherIcon.setBackgroundResource(R.drawable.yin);
                } else {
                    weatherIcon.setBackgroundResource(R.drawable.sun);
                }
//                tv_weather.setText(weather + "\t" + mapList.get(2).get("wendu") + " ℃");
            } else {
//                tv_weather.setText("获取天气信息失败");
            }
        } else if (flag == 5) { //班牌模式
            getBanPaiModelResponse response = (getBanPaiModelResponse) object;
            if (!response.Model.equals("Common")) {
                // 跳到加载页面
                startActivity(new Intent(V_SMainActivity.this, AlaunchActivity.class));
            }
        }
    }

    @Override
    public void fail(int flag, String errMsg) {
        if (flag == 2 || flag == 3) {
            isScanCard = false;
            isNew = true;
        }else if(flag == 1){
            startActivityForResult(new Intent(V_SMainActivity.this, SettingActivity.class), COMETOSET);
        }
        ToastUtil.showToast(this, errMsg);
    }


    /**
     * 刷卡回调函数实现
     */
//    static {
//        System.loadLibrary("serial_port");
//    }

    private boolean isNew = true;

    @Override
    protected void onDataReceived(final byte[] buffer, final int size) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (Env.getAppContext().isInitial) {
                    if (cardCode != null) {
                        if (isNew) {
                            isNew = false;
                            cardCode = "";
                        }
                        cardCode += new String(buffer, 0, size);
                        handler.removeMessages(MSG_TWO);
                        handler.sendEmptyMessageDelayed(MSG_TWO, 1000);
                    }
                } else {
                    ToastUtil.showToast(V_SMainActivity.this, " 初始化失败！");
                    startActivityForResult(new Intent(V_SMainActivity.this, SettingActivity.class), COMETOSET);
                }
                backTime = Env.getAppContext().backToMainTime * 60;
            }
        });


    }


    /**
     *
     */
    public static final int POSTPHOTO = 100;
    public static final int COMETOSET = 101;
    private String filePath = "";

    /**
     * 存放上传图片返回来的地址路径
     */

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Bundle bundle = data.getExtras();
        switch (requestCode) {
            case COMETOSET:
                boolean flag = bundle.getBoolean("reSetClass", false);
                if (flag) {
                    startActivity(new Intent(V_SMainActivity.this, AlaunchActivity.class));
                }
                break;
//            case POSTPHOTO:
//                String fileinfo = bundle.getString("back");
//                try {
//                    JSONObject myJsonObject = new JSONObject(fileinfo);
//                    filePath = myJsonObject.getString("FilePath");
//                    Log.i("onActivityResult: ", filePath);
//                    ToastUtil.showToast(V_SMainActivity.this, "扫描学号：" + cardCode);
//                    mPresenter.login(cardCode, filePath);
//                } catch (Exception ex) {
//                    Env.error(ex);
//                }
//                break;
            default:
                break;
        }
    }

    /**
     * handle机制更新页面
     */
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_ONE:
                    ThreadPoolFactory.getThread().execute(getTimeBySecondToView);
                    break;
                case MSG_TWO:
                    if (!isScanCard) {
                        isScanCard = true;
                        String code = cardCode.replaceAll("\r", "").replaceAll("\n", "").trim();
                        cardCode = EscapeUnescapeUtil.StringTo10(code);
//                        if (Env.getAppContext().isAutoTakePhoto) {
//                            ToastUtil.showToast(V_SMainActivity.this, "拍照中，请对准摄相头：" + cardCode);
//                            Intent intent = new Intent();
//                            intent.setClass(V_SMainActivity.this, CameraActivity.class);
//                            startActivityForResult(intent, POSTPHOTO);
//                        } else {
                        if (!code.contains("\u0003\u0002")) {
                            isScanCard = true;
                            ToastUtil.showToast(V_SMainActivity.this, "扫描学号：" + cardCode);
                            mPresenter.login(cardCode);
                        } else {
                            ToastUtil.showToast(V_SMainActivity.this, "读卡失败，请不要一直刷卡，听到嘀一声就可以了");
                        }

//                        }
                    } else {
                        ToastUtil.showToast(V_SMainActivity.this, "正在通信中,不用再次刷卡");
                    }
                    break;
                case MSG_THREE:
                    isLockSet = true;
                    if (isLock) {
                        int uiFlags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE;
                        getWindow().getDecorView().setSystemUiVisibility(uiFlags);
                    } else {
                        int uiFlags = View.SYSTEM_UI_FLAG_VISIBLE;
                        getWindow().getDecorView().setSystemUiVisibility(uiFlags);
                    }
                    isLockSet = false;
                    break;
            }
        }
    };


    /**
     * getTimeBySecond 每秒获取系统时间，对应handle的MSG_ONE
     */
    private Runnable getTimeBySecond = new Runnable() {
        @Override
        public void run() {
            do {
                try {
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = MSG_ONE;
                    handler.sendMessage(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (true);
        }
    };
    /**
     * getTimeBySecondToView 更新时间 监听班牌模式
     */
    private Runnable getTimeBySecondToView = new Runnable() {
        @Override
        public void run() {
            if (!isActivity) {
                final String data = getTimeAndWeatherUtil.getTimeAndData();
                final String[] value = data.split(" ");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        /***时间的更新*/
                        tv_data.setText(value[2] + "\n" + value[0]);
                        tv_time.setText(value[1]);

                        /*** 登录时间的更新*/
                        if (currentLoginTime >= 0) {
                            if (currentLoginTime == 0) {
                                Env.getAppContext().StudentID = "";
                                tvloginTime.setVisibility(View.INVISIBLE);
                                img_loginTime.setVisibility(View.INVISIBLE);
                                home1.performClick();
                            }
                            currentLoginTime--;
                            tvloginTime.setText(currentLoginTime + "");
                        }
                        /***返回主界面时间的更新*/
                        if (backTime >= 0) {
                            if (backTime == 0) {
                                home1.performClick();
                            }
                            backTime--;
                        }
                    }
                });

                /**监听班牌模式*/
                mPresenter.getBanPaiModel();
                mPresenter.getWeather("101270101");

            }
        }
    };

    /**
     * 监听reclycleView的滚动
     */
    public static RecyclerView.OnScrollListener listener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            backTime = Env.getAppContext().backToMainTime * 60;
        }
    };

    /**
     * 监听底部的虚拟按键隐藏 对应handle 的 MSG_THREE
     */
    private View.OnSystemUiVisibilityChangeListener UiVisibilityChangeListener = new View.OnSystemUiVisibilityChangeListener() {
        @Override
        public void onSystemUiVisibilityChange(int visibility) {
            if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
                if (!isLockSet) {
                    handler.sendEmptyMessage(MSG_THREE);
                }
            }
        }
    };


    @Override
    protected void onResume() {
        super.onResume();
        isActivity = false;
    }


    @Override
    protected void onPause() {
        super.onPause();
        isActivity = true;

    }


}
